package controllers.admin;

import admin.AdminBusiness;
import admin.AdminUser;
import controllers.auth.Secure;
import controllers.baseAPI.BaseJsonAPI;
import enums.DeletedStatus;
import org.apache.commons.lang.StringUtils;
import param.admin.AdminBusinessRequest;
import play.Logger;
import play.data.validation.Required;
import play.i18n.Messages;
import play.mvc.With;
import response.admin.AdminBusinessDTO;
import utils.ConvertUtil;

import javax.validation.Valid;
import java.util.*;

/**
 * Created by liming on 16/6/29.
 */
//@With(Secure.class)
public class AdminBusinessCtrl extends BaseJsonAPI {

    public static void index(){

        renderSuccMessage("链接成功~~");
    }

    //加载
    public static void index(String name) {
        List<AdminBusiness> adminBusinesses = new ArrayList<>();
        if(StringUtils.isNotBlank(name)){
            name = "%" + name + "%";
            List<AdminBusiness> businessList  = AdminBusiness.loadAllBusiness(name);
            for(AdminBusiness adminBusiness : businessList){
                adminBusinesses.add(adminBusiness);
                List<AdminBusiness> childBussiness = AdminBusiness.loadAllBusinessByParentId(    adminBusiness.id);
                for(AdminBusiness child : childBussiness){
                    adminBusinesses.add(child);
                }
            }
        }else{
            adminBusinesses = AdminBusiness.loadAllBusiness();
        }

        Map<String, Object> dataMap = new HashMap<>();
        if(adminBusinesses.size() == 0 ){
            dataMap.put("rows",adminBusinesses);
            dataMap.put("flag",false);
            dataMap.put("total",0);
        }else{
            dataMap.put("rows",adminBusinesses);
            dataMap.put("flag",true);
            dataMap.put("total",adminBusinesses.size());
        }
        renderJSON(dataMap);
    }

    //新建
    public static void create() {
        Logger.info("LOGGER AdminBusinessAPI 0225164700002 create 创建业务-----");
        //权限验证
//        if (!checkAuth("AdminBusinessAPI", "create"))
//            renderWarnMessage(407, Messages.get("flash.warn.no-permission"));

        AdminBusinessRequest businessRequest = validateRequestBody("business", AdminBusinessRequest.class);

        AdminUser loginUser = Secure.getLoginUser();
        AdminBusiness adminBusiness = AdminBusiness.create(businessRequest,loginUser);
        flash.put("notice", Messages.get("flash.notice.save-success"));
        AdminBusinessDTO businessResponse = AdminBusinessDTO.from(adminBusiness);
        renderData(businessResponse);

    }

    /**
     * 显示详情.
     */
    public static void show(String id) {
        AdminBusiness adminBusiness = AdminBusiness.findByBusinessId(id);
        if (adminBusiness == null)
            renderWarnMessage(404, "角色不存在，可能已经被删除！");
        AdminBusinessDTO adminBusinessResponse = AdminBusinessDTO.from(adminBusiness);
        renderData(adminBusinessResponse);
    }

    //修改

    public static void modfiy(@Valid @Required String id) {
        Logger.info("LOGGER AdminBusinessAPI 0225164700003 modfiy 修改业务-----");

//        if (!checkAuth("AdminBusinessAPI", "modfiy"))
//            renderWarnMessage(407, Messages.get("flash.warn.no-permission"));

        AdminBusinessRequest businessRequest = validateRequestBody("business", AdminBusinessRequest.class);

        if (businessRequest == null) {
            renderWarnMessage(404, Messages.get("adminBusiness.no-exists"));
        }
        AdminBusiness adminBusiness = AdminBusiness.findByBusinessId(id);

        if (adminBusiness == null) {
            renderWarnMessage(404, Messages.get("adminBusiness.no-exists"));
        }
        notFoundIfNull(adminBusiness);

        AdminUser loginUser = Secure.getLoginUser();
        AdminBusiness.modfiy(id, businessRequest , loginUser);
        AdminBusinessDTO businessResponse = AdminBusinessDTO.from(adminBusiness);
        flash.put("notice", Messages.get("flash.notice.update-success"));


        renderData(businessResponse);

    }

    /**
     * 删除(可批量)
     * //     * @param idsStr
     * idsStr 为需要删除的业务ID，用","隔开
     */
    public static void delete(@Valid @Required String[] ids) {
        Logger.info("LOGGER AdminBusinessAPI 0225164700003 delete 删除业务-----");
        Logger.info("--------------- 删除的业务ids :%s", ConvertUtil.toJson(ids));

//        if (!checkAuth("AdminBusinessAPI", "delete"))
//            renderWarnMessage(407, Messages.get("flash.warn.no-permission"));

        AdminUser loginUser = Secure.getLoginUser();
        Logger.info("LOGGER AdminBusinessAPI   delete   0223163700001  删除业务功能 ，操作人:%s , 操作人ID： %s", loginUser != null?loginUser.name: "" , loginUser);
        Date nowtime = new Date();
        if (ids != null) {
            for (String id : ids) {
                AdminBusiness business = AdminBusiness.findByBusinessId(id);
                if (business != null) {
                    business.deleted = DeletedStatus.DELETED;
                    business.modifyAt = nowtime;
                    business.modifyUser = loginUser;
                    business.save();

                    if (AdminBusiness.checkBrotherNode(business.parentId) == 0) {
                        AdminBusiness parent = AdminBusiness.findById(business.parentId);
                        parent.isLeaf = true;
                        parent.save();
                    }
                }
            }
        }
        flash.put("notice", Messages.get("flash.notice.delete-success", "业务功能"));

        renderSuccMessage("删除成功！");

    }


}
